var HttpStatus = new Object();
HttpStatus.UNAUTHORIZED = 401;
HttpStatus.SUCCESS = 200;
var ojurl = "http://localhost/OnlineJudge";
var tokenName = "contestToken";
var localName = "contestName";
var statusPageSize = 10;   //status页面每页数据

function getName(name) {
    var t = localStorage.getItem(name);
    if (t != null) {
        return t.toString();
    }
    return null;
}
function setName(name, a) {
    localStorage.setItem(name, a);
}
function removeName(name) {
    localStorage.removeItem(name);
}
function logout() {
    localStorage.clear();
    sessionStorage.clear();
    window.location.href = "/front/contest";
}


function getUrlVar(variable) {
    var query = window.location.search.substring(1);
    var vars = query.split("&");
    for (var i=0; i<vars.length; ++i) {
        var pair = vars[i].split("=");
        if (pair[0] == variable) {
            return pair[1];
        }
    }
    return null;
}
function base26Sytem(i) {   //10进制转26进制
    i = Number(i);
    var ret = "";
    if (i==0) {
        ret = ret + "A";
    }
    while(i!=0) {
        ret = ret + String.fromCharCode(Number("A".charCodeAt()) + parseInt(i%26));
        i = parseInt(i/26);
    }
    return ret.split('').reverse().join('');   //反转
}
function base26SytemToDec(t) {  //26进制转10进制
    t = String(t).toUpperCase();
    var ret = Number(0);
    var len = t.length;
    for (var i=0; i<len; ++i) {
        ret = ret * 26 + parseInt(Number(t[i].charCodeAt()-'A'.charCodeAt()));
    }
    return ret;
}
function isBlank(arg) {
    if (arg == null || arg == "") {
        return true;
    }
    var len = arg.length;
    for (var i=0; i<len; ++i) {
        if (arg[i] != ' ') {
            return false;
        }
    }
    return true;
}

function clearTbody(arg) {
    var tableList = document.getElementById(arg);
    var tbodys = tableList.getElementsByTagName("tbody");
    var len = tbodys.length;
    for (var i=0; i<len; ++i) {
        tableList.removeChild(tbodys[i]);
    }
}
function min(var1, var2) {
    if (var1 < var2) {
        return var1;
    }
    return var2;
}
function max(var1, var2) {
    if (var1 > var2) {
        return var1;
    }
    return var2;
}

// contest problem start
function timer() {
    date = Date.parse(document.getElementById("now").textContent);
    etime = Date.parse(document.getElementById("end").textContent);
    date += 1000;
    // console.log(new Date(date));
    document.getElementById("now").textContent = (new Date(date)).format("yyyy-MM-dd hh:mm:ss");
    if(date < etime) {
        setTimeout("timer()", 1000);
    }
    else {
        document.getElementById("state").innerHTML = "<span style='color: red'>Contest is End</span>"
    }
}

function showInfo(data) {
    var content = data.notification.split(";");
    var len = content.length;
    var notification = "<ul>";
    for (var i=0; i<len; ++i) {
        notification += "<li>" + content[i] + "</li>";
    }
    notification += "</ul>";
    document.getElementById("notification").innerHTML = notification;
    document.getElementById("title").innerHTML = data.title;
    if (data.private == true) {
        document.getElementById("type").innerHTML = "Private";
        document.getElementById("type").className = "label label-warning";
    }
    else {
        document.getElementById("type").innerHTML = "Public";
        document.getElementById("type").className = "label label-success";
    }
    var time = data.nowTime;
    var endtime = data.endTime;

    Date.prototype.format = function(fmt) { 
        var o = { 
            "M+" : this.getMonth()+1,                 
            "d+" : this.getDate(),                    
            "h+" : this.getHours(),                   
            "m+" : this.getMinutes(),                 
            "s+" : this.getSeconds(),                
            "q+" : Math.floor((this.getMonth()+3)/3), 
            "S"  : this.getMilliseconds()             
        }; 
        if(/(y+)/.test(fmt)) {
                fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length)); 
        }
        for(var k in o) {
            if(new RegExp("("+ k +")").test(fmt)){
                fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
            }
        }
        return fmt; 
    }
    document.getElementById("now").textContent = time;
    document.getElementById("end").textContent = endtime;
    timer();
}


function showProblemList(data) {
    var tbody = document.createElement("tbody");
    clearTbody("tableList");
    document.getElementById("tableList").appendChild(tbody);
    var len = data.length;
    var contestId = getUrlVar("contestId");
    for (var i=0; i<len; ++i) {
        tbody.insertRow(i);
        var tl = tbody.rows[i];
        var problem = data[i];
        if (i%2 == 1) {
            tl.className = "line-2";
        }
        tl.insertCell(0);
        if (problem.solved != null) {
            if (problem.solved == 0) {
                tl.cells[0].innerHTML = "?";
            }
            else if (problem.solved == 1) {
                tl.cells[0].innerHTML = "✓";
            }
        }
        tl.insertCell(1); tl.cells[1].innerHTML = problem.problemId;
        tl.insertCell(2); tl.cells[2].innerHTML = "<a href='problemInfo?contestId="+contestId+"&problemId="+i+"'>" + problem.title + "</a>";
        var submit = problem.submit;
        var accept = problem.accept;
        tl.insertCell(3);
        if (submit==null || submit == 0) {
            tl.cells[3].innerHTML = "0";
        }
        else {
            var t = accept/submit*100;
            tl.cells[3].innerHTML = String(t.toFixed(2)) + "% (" + accept + "/" + submit + ")";
        }
    }
}
// contest problem end

// contest problem page start
function loadProblem(docType) {
    var contestId = getUrlVar("contestId");
    var problemId = getUrlVar("problemId");
    var problemUrl = ojurl + "/contest/problem/"+problemId+"."+docType+"?contestId="+contestId;
    if (docType == "pdf") {
        document.getElementById("problemContent").href = problemUrl;
        $("a.media").media({
            width:  "100%",
            height: "700"
        });
    }
    else if (docType == "html") {
        document.getElementById("content").innerHTML 
        = '<iframe src="' + problemUrl + '" style="zoom: 50%" width="100%" height="1600"></iframe>';
    }
    else if (docType == "md") {
        $.get({
            url: problemUrl,
            success: function(md) {
                editormd.markdownToHTML("content", {
                    markdown        : md ,
                    htmlDecode      : "style,script,iframe",
                    tocm            : true,
                    emoji           : true,
                    taskList        : true,
                    tex             : true,  // 默认不解析
                });
            }
        });
    }
    else {
        alert("error!");
    }
}
function showProblemInfo(data) {
    document.getElementById("pid").innerHTML = data.problemId;
    if (data.isSpj == true) {
        document.getElementById("spj").innerHTML = "Yes";
    }
    else {
        document.getElementById("spj").innerHTML = "No";
    }
    document.getElementById("tl").innerHTML = String(data.timeLimit*1000) + "MS";
    document.getElementById("stl").innerHTML = String(data.timeLimitSpc*1000) + "MS";
    document.getElementById("ml").innerHTML = String(data.memoryLimit) + "M";
    document.getElementById("submits").innerHTML = String(data.submit);
    document.getElementById("accepted").innerHTML = String(data.accept);
    document.getElementById("title").innerHTML = data.title;
    loadProblem(data.docType);
}
// contest problem page end


// contest status start

var myLan = ["GCC", "G++", "Java", "Pascal", "Python", "UNKNOWN"];
function getLan(arg) {
    return myLan[arg-1];
}
var myRes = [
    ["Accepted", "ac"],
    ["Memory Limit Exceeded", "err"],
    ["Time Limit Exceeded", "tl"],
    ["Runtime Error", "err"],
    ["Output Limit Exceeded", "err"],
    ["Dangerous Call", "err"],
    ["Compile Error", "ce"],
    ["Wrong Answer", "wa"],
    ["Presentation Error", "pe"],
    ["Waiting", ""]
]
function getRes(arg) {
    if (arg == null) {
        arg = 9;
    }
    return myRes[arg];
}
function showStatus(data, contestId) {
    // console.log(data);
    var allPages = data.allPages;
    var nowPage = data.nowPage;
    var content = data.list;
    var len = content.length;
    var tbody = document.createElement("tbody");
    var myName = getName(localName);
    clearTbody("tableList");
    document.getElementById("tableList").appendChild(tbody);
    for(var i=0; i<len; ++i) {
        tbody.insertRow(i);
        var tl = tbody.rows[i];
        var myStatus = content[i];
        if (i%2 == 1) {
            tl.className = "line-2";
        }
        var solutionText = null;
        if (myName != null && myName == myStatus.userName) {
            solutionText = "<a href='javascript:void(0);' style='border-style: solid; border-width: thin' onclick='showCode(" +
                           myStatus.solutionId + "," + contestId + ")'>" + 
                           String(myStatus.solutionId) + "</a>";
        }
        else {
            solutionText = String(myStatus.solutionId);
        }
        tl.insertCell(0); tl.cells[0].innerHTML = solutionText;
        tl.insertCell(1); tl.cells[1].innerHTML = "<a href='problemInfo?contestId="+contestId+"&problemId=" + myStatus.problemId + "'>" + base26Sytem(myStatus.problemId) + "</a>";
        tl.insertCell(2); tl.cells[2].innerHTML =  myStatus.userName; //"<a href='user?contestId="+contestId+"&userName=" + myStatus.userName + "'>" + myStatus.userName + "</a>";
        tl.insertCell(3); tl.cells[3].innerHTML = getLan(myStatus.lang);
        var res = getRes(myStatus.state);
        tl.insertCell(4); tl.cells[4].innerHTML = res[0]; tl.cells[4].className = res[1];
        tl.insertCell(5);
        tl.insertCell(6);
        if (myStatus.state != null) {
            tl.cells[5].innerHTML = String(myStatus.maxMemory) + "KB";
            tl.cells[6].innerHTML = String(myStatus.time) + "ms";
        }
        tl.insertCell(7); tl.cells[7].innerHTML = String(myStatus.codeLength) + "B";
        tl.insertCell(8); tl.cells[8].innerHTML = myStatus.submitTime;
    }
    document.getElementById("pageInput").value = nowPage;
    document.getElementById("nowPage").innerHTML = nowPage;

    var t = "goPage(" + max(Number(nowPage)-1, 1) + ")";
    document.getElementById("pre").onclick = Function(t);
    t = "goPage(" + min(Number(nowPage)+1, allPages) + ")";
    document.getElementById("next").onclick = Function(t);
    t = "goPage(" + String(allPages) + ")";
    document.getElementById("end").onclick = Function(t); 
}

// contest status end

// rank list start
function sovleTime(a) {
    if (a == null) {
        a=0;
    }
    var symbol = "";
    if (a < 0) {
        a = -a;
        symbol = "-";
    }
    var ret = "";
    ret += String(parseInt(a/3600)) + ":";
    ret += String(parseInt(a%3600/60)) + ":";
    ret += String(a%60);
    return symbol + ret;
}
function showRankList(data) {
    var problemCount = data.problemCount;
    var m = problemCount;
    var list = data.list;
    var n = Number(list.length);
    var matrix = new Array(n);
    for (var i=0; i<n; ++i) {
        matrix[i] = new Array(m);
        for (var j=0; j<m; ++j) {
            matrix[i][j] = new Object();
        }
    }
    for (var i=0; i<n; ++i) {
        var t = list[i];
        var solvedList = t.solvedList;
        var solvedLen = solvedList.length;
        var firstSolvedList = t.firstSolvedList;
        var firstSolvedListLen = firstSolvedList.length;
        for (var j=0; j<solvedLen; ++j) {
            var mark = solvedList[j].problemId;
            matrix[i][mark].acceptTime = solvedList[j].acceptTime;
            matrix[i][mark].try = solvedList[j].try;
        }
        for (var j=0; j<firstSolvedListLen; ++j) {
            matrix[i][firstSolvedList[j]].firstAc = true;
        }
    }
    var table = document.getElementById("tableList");
    var thead = document.createElement("thead");
    table.appendChild(thead);
    var theadRow = thead.insertRow();
    theadRow.insertCell(0); theadRow.cells[0].innerHTML = "Rank"; //theadRow.cells[0].style = "width: 1em";
    theadRow.insertCell(1); theadRow.cells[1].innerHTML = "Team"; //theadRow.cells[1].style = "width: 1em";
    theadRow.insertCell(2); theadRow.cells[2].innerHTML = "Solved"; //theadRow.cells[2].style = "width: 1em";
    theadRow.insertCell(3); theadRow.cells[3].innerHTML = "Penalty"; //theadRow.cells[3].style = "width: 1em";
    theadRow.insertCell(4); theadRow.cells[4].innerHTML = "School"; //theadRow.cells[4].style = "width: 1em";
    for (var i=0; i<m; ++i) {
        theadRow.insertCell(i+5);
        theadRow.cells[i+5].innerHTML = base26Sytem(i);
        theadRow.cells[i+5].style = "width: 6em";
    }
    clearTbody("tableList");
    var tbody = document.createElement("tbody");
    table.appendChild(tbody);
    for (var i=0; i<n; ++i) {
        tbody.insertRow(i);
        var rank = tbody.rows[i];
        var user = list[i];
        rank.insertCell(0); rank.cells[0].innerHTML = i+1;
        rank.insertCell(1); rank.cells[1].innerHTML = user.team;
        rank.insertCell(2); rank.cells[2].innerHTML = user.solved;
        rank.insertCell(3); rank.cells[3].innerHTML = sovleTime(user.penalty);
        rank.insertCell(4); rank.cells[4].innerHTML = user.school;
        for (var j=0; j<m; ++j) {
            rank.insertCell(j+5);
            var t = matrix[i][j];
            if (t.try != null) {
                if (t.acceptTime != null) {
                    rank.cells[j+5].innerHTML = sovleTime(t.acceptTime) + "(" + (t.try-1) + ")";
                    if (t.firstAc!=null && t.firstAc==true) {
                        rank.cells[j+5].className = "rank-aac";
                    }
                    else {
                        rank.cells[j+5].className = "rank-ac";
                    }
                }
                else {
                    rank.cells[j+5].innerHTML = "(-" + t.try + ")";
                    rank.cells[j+5].className = "rank-err";
                }
            }
        }
    }
}
// rank list end

//login start

//login end